package com.xadmin.sys.rbac.controller;


import com.xadmin.sys.common.response.Result;
import com.xadmin.sys.common.utils.Page;
import com.xadmin.sys.rbac.mapper.UserMapper;
import com.xadmin.sys.rbac.pojo.Menu;
import com.xadmin.sys.rbac.pojo.Role;
import com.xadmin.sys.rbac.pojo.User;
import com.xadmin.sys.rbac.pojo.UserAndRole;
import com.xadmin.sys.rbac.service.MenuService;
import com.xadmin.sys.rbac.service.UserService;
import com.xadmin.sys.rbac.vo.MenuVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.xadmin.sys.rbac.utils.Convert.convertToMenuVo;
import static com.xadmin.sys.rbac.utils.FindChild.findMenuChild;
import static com.xadmin.sys.rbac.utils.FindRoot.findMenuRoot;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author vic Ly
 */
@RestController

@RequestMapping("/user")
@Api(value = "系统用户模块",tags = "系统用户接口")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private MenuService menuService;


    @PreAuthorize("hasRole('SUPERADMIN')")
    @RequestMapping(value = "/userList",method = RequestMethod.POST)
    @ApiOperation(value = "分页查询用户信息",notes = "分页查询用户信息")
    public Result getByPage(@RequestBody Page<User> page){
        page = userService.getAllByPage(page);
        return  Result.ok().data("data",page);
    }

    @PreAuthorize("hasRole('SUPERADMIN')")
    @RequestMapping(value = "/getRolesByUId/{id}",method = RequestMethod.GET)
    @ApiOperation(value = "查询某个用户角色信息",notes = "查询某个用户角色信息")
    public Result getRolesByUId(@PathVariable Integer id){
        List<Role> roles= userService.getRoleByUserId(id);
        return  Result.ok().data("data",roles);
    }

    @RequestMapping(value = "/addUser",method = RequestMethod.POST)
    @ApiOperation(value = "添加用户",notes = "添加用户")
    public Result addUser(@RequestBody User user){
        if(StringUtils.isBlank(user.getPassword())){
            user.setPassword(new BCryptPasswordEncoder().encode("123456"));
        }else {
            user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        }
        User u = userService.getByName(user.getUsername());
        if(u==null){
            boolean  check =userService.save(user);
            return  Result.ok().message("添加成功！");
        }else {
            return Result.error().message("用户已存在！");
        }
    }

    @PreAuthorize("hasRole('SUPERADMIN')")
    @RequestMapping(value = "/deleteUser/{id}",method = RequestMethod.DELETE)
    @ApiOperation(value = "根据ID删除用户",notes = "根据ID删除用户")
    public Result deleteUser(@PathVariable Integer id){
        boolean check = userService.removeById(id);
        if (check == true){
            return  Result.ok().message("删除成功！");
        }else{
            return Result.error().message("删除失败！");
        }
    }

    @PreAuthorize("hasRole('SUPERADMIN')")
    @RequestMapping(value = "/viewUser/{id}",method = RequestMethod.GET)
    @ApiOperation(value = "根据ID查看用户信息",notes = "根据ID查看用户信息")
    public Result viewUser(@PathVariable Integer id){
        User user = userService.getById(id);
        return  Result.ok().data("data",user);
    }

    @RequestMapping(value = "/update",method = RequestMethod.PUT)
    @ApiOperation(value = "根据ID更新用户信息",notes = "根据ID更新用户信息")
    public Result update(@RequestBody User user){
        if(!StringUtils.isBlank(user.getPassword())){
            user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        }
        int check = userMapper.updateById(user);
        if (check != 0){
            return  Result.ok().message("更新成功！");
        }else{
            return Result.error().message("更新失败！");
        }
    }


    @PreAuthorize("hasRole('SUPERADMIN')")
    @RequestMapping(value = "/addRoles/{id}",method = RequestMethod.POST)
    @ApiOperation(value = "为用户批量添加角色",notes = "为用户批量添加角色")
    @Transactional(rollbackFor = Exception.class)
    public Result addRoles(@RequestBody Integer[] ids, @PathVariable Integer id){
        List<UserAndRole> idList = new ArrayList<>();
        for(int i = 0;i<ids.length;i++){
            UserAndRole ur = new UserAndRole();
            ur.setUserId(id);
            ur.setRoleId(ids[i]);
            idList.add(ur);
        }
        userService.deleteRoles(id);
        int number = userService.addRoles(idList);
        if (number != 0){
            return  Result.ok().message("分配成功！");
        }else{
            return Result.error().message("分配失败！");
        }
    }

    @RequestMapping(value = "/getByUserName",method = RequestMethod.GET)
    @ApiOperation(value = "根据用户名字查看用户信息",notes = "根据用户名字查看用户信息")
    public Result getByUserName(@RequestParam String username){
        User user = userService.getByName(username);
        return  Result.ok().data("data",user);
    }

    @RequestMapping(value = "/getUserMenu/{id}",method = RequestMethod.GET)
    @ApiOperation(value = "根据ID查询用户权限",notes = "根据ID查询用户权限")
    public Result getUserMenu(@PathVariable Integer id){
        List<Menu> menuList = userService.getMenuByUserId(id);
        /*将menuList转换成menuVoList*/
        List<MenuVo> menuVoList = convertToMenuVo(menuList);
        /*找根节点*/
        List<MenuVo> rootMenu = findMenuRoot(menuVoList);
        /*为根节点设置子菜单*/
        for(MenuVo menuVo : rootMenu){
            /*获取某个根节点的子菜单*/
            List<MenuVo> childList = findMenuChild(menuVo.getId(),menuVoList);
            menuVo.setChildren(childList);
        }
        List<Integer> ids = menuService.findOpenIds();
        Map<String, Object> map = new HashMap<>();
        map.put("tree", rootMenu);
        map.put("open", ids);
        return  Result.ok().data("data",map);
    }

}

